package com.csw.shoppingCartServlet.service;

import java.sql.Connection;

import com.csw.shoppingCartServlet.dao.UserDao;
import com.csw.shoppingCartServlet.dao.UserDaoImpl;
import com.csw.shoppingCartServlet.entity.User;
import com.csw.shoppingCartServlet.util.JDBCUtils;

public class UserServiceImpl implements UserService {

	@Override
	public User queryBy(String username, String password) {

		Connection connection = null;

		try {
			connection = JDBCUtils.getConnection();
			connection.setAutoCommit(false);
			UserDao ud = new UserDaoImpl();
			User user = ud.query(username, password);
			connection.commit();
			return user;
		} catch (Exception e) {

			try {
				if (connection!=null) {
					connection.rollback();
				}
			} catch (Exception e2) {

				e2.printStackTrace();
			}
			e.printStackTrace();
			throw new RuntimeException("{[service query by error}}");
		} finally {
			JDBCUtils.close(connection);
		}

	}

	@Override
	public void addUsers(User uu) {

		Connection connection = null;
		try {
			connection = JDBCUtils.getConnection();
			connection.setAutoCommit(false);
			UserDao ud = new UserDaoImpl();
			ud.addUsers(uu);

			connection.commit();

		} catch (Exception e) {

			try {
				if (connection!=null) {
					connection.rollback();
				}
			} catch (Exception e2) {

				e2.printStackTrace();
			}
			e.printStackTrace();
			throw new RuntimeException("{[service insert into error}}");
		} finally {
			JDBCUtils.close(connection);
		}

	}

	@Override
	public void changePassword(String newPass1, String username) {
		Connection connection = null;
		try {
			connection = JDBCUtils.getConnection();
			connection.setAutoCommit(false);
			UserDao ud = new UserDaoImpl();
			ud.changePassword(newPass1, username);

			connection.commit();
			System.out.println("{{service changePassword success}}");
		} catch (Exception e) {

			try {
				if (connection!=null) {
					connection.rollback();
				}
			} catch (Exception e2) {

				e2.printStackTrace();
			}
			e.printStackTrace();
			throw new RuntimeException("{{service changePassword error}}");
		} finally {
			JDBCUtils.close(connection);
		}
	}

	@Override
	public void updateBy(User uu) {
		Connection connection = null;
		try {
			connection = JDBCUtils.getConnection();
			connection.setAutoCommit(false);
			UserDao ud = new UserDaoImpl();
			ud.updateBy(uu);

			connection.commit();
			System.out.println("{{service changePassword success}}");
		} catch (Exception e) {

			try {
				if (connection!=null) {
					connection.rollback();
				}
			} catch (Exception e2) {

				e2.printStackTrace();
			}
			e.printStackTrace();
			throw new RuntimeException("{{service changePassword error}}");
		} finally {
			JDBCUtils.close(connection);
		}
	}
}
